package com.bianguo.android.ioclibrary;

import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;

import com.bianguo.android.ioclibrary.enums.NetworkState;

/**
 * 网络监听回调，结合ConnectivityManager使用
 * manager.requestNetwork(new NetworkRequest.Builder().build(), networkCallback);
 */
public class NetworkCallback extends ConnectivityManager.NetworkCallback {

    //网络可用
    @Override
    public void onAvailable(Network network) {
        super.onAvailable(network);
        NetworkManager.getDefault().post(NetworkState.AUTO);
    }

    //网络不可用
    @Override
    public void onLost(Network network) {
        super.onLost(network);
        NetworkManager.getDefault().post(NetworkState.NONE);
    }

    @Override
    public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
        super.onCapabilitiesChanged(network, networkCapabilities);
        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                //wifi网络
                NetworkManager.getDefault().post(NetworkState.WIFI);
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                //蜂窝网络
                NetworkManager.getDefault().post(NetworkState.CELLULAR);
            }
        }
    }
}
